import Cookies from 'js-cookie'
import type { Router } from 'vue-router'

interface UserRole {
    role: 'admin' | 'counselor' | 'user'
}

const roleRouteMap = {
    admin: ['/admin/dashboard', '/admin/users', '/admin/settings', '/admin/roles', '/admin/counselors', '/admin/appointments', '/admin/consultation-records', '/admin/announcements'],
    counselor: ['/admin/appointments', '/admin/consultation-records', '/admin/counselor-profile'],
    user: ['/admin/appointments', '/admin/consultation-records']
}

export function setupRouterGuard(router: Router) {
    router.beforeEach((to, from, next) => {
        const token = Cookies.get('api-token')
        const userRole = Cookies.get('user-role') as UserRole['role']
        const whiteList = ['/login', '/register', '/'] // 白名单，不需要登录也可以访问的页面

        if (whiteList.includes(to.path)) {
            // 在白名单中的页面，直接放行
            next()
            return
        }

        if (!token) {
            // 未登录且访问的不是白名单页面，重定向到登录页
            next(`/login?redirect=${to.path}`)
            return
        }

        if (to.path === '/login') {
            // 已登录状态下访问登录页面，根据用户角色重定向到对应的首页
            if (userRole === 'admin') {
                next('/admin/dashboard')
            } else if (userRole === 'counselor') {
                next('/admin/counselor-profile')
            } else {
                next('/admin/appointments')
            }
            return
        }

        // 检查用户是否有权限访问该路由
        const allowedRoutes = roleRouteMap[userRole] || []
        if (allowedRoutes.includes(to.path)) {
            next()
        } else {
            // 根据用户角色重定向到对应的首页
            if (userRole === 'admin') {
                next('/admin/dashboard')
            } else if (userRole === 'counselor') {
                next('/admin/counselor-profile')
            } else {
                next('/admin/appointments')
            }
        }
    })
}